<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
    <!-- load css -->
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/layui/css/font/iconfont.css}" media="all"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/layui/js/layui/css/layui.css}"  media="all"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/bootstrap/bootstrap/css/bootstrap.min.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/bootstrap-table/bootstrap-table.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/css/table.css}"  media="all"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/bootstrap/bootstrap/css/bootstrap.min.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/plugin/layui/js/select2/css/select2.css}" media="all"/>

    <style>
        h2{
             margin: 0;
         }
        .blocks{
            display: flex;
            flex-direction: column;
            width: 20rem;
            height: 6rem;
        }
        .blockout{
            display: flex;
            justify-content: space-between;
            margin: 1.5rem 0;
            padding: 0 1rem;
        }
        input[type="text"]:disabled{
            background-color: #EEF1F6;
        }
        input[type="text"]{
            height: 3rem;
        }
        #addInf{
            display: none;
        }
        #addInfor{
            display: none;
            width: 5rem;
            margin-top: 2rem;
            margin-left: 1rem;
        }
    </style>
</head>
<body>
<div class="layui-fluid larry-wrapper" id="StandardVUE">
    <div class="layui-row layui-col-space30">
        <div class="layui-col-xs24">
            <div class="layui-collapse">
                <div class="layui-colla-item" id="addInf">
                    <h2 class="layui-colla-title">新增明细</h2>
                    <div class="layui-colla-content layui-show">
                        <form id="form1" class="layui-form layui-form-pane" action="">
                            <div class="blockout">
                                <div class="blocks">
                                    <label>货品编号</label>
                                    <div class="layui-input-inline" id="goodsCodeS">
                                        <select type="text"
                                                lay-filter="goodsCode"
                                                lay-search=""
                                                lay-verify="required"
                                                id="goodsCode"
                                                name="goodsCode"
                                                placeholder="货品编号">
                                        </select>
                                    </div>
                                </div>
                                <div class="blocks">
                                    <label>货品名称</label>
                                    <div class="layui-input-inline">
                                        <input type="text" disabled class="layui-input" name="goodsName" id="goodsName" placeholder="货品名称"/>
                                    </div>
                                </div>
                                <div class="blocks">
                                    <label>包装名称</label>
                                    <div class="layui-input-inline">
                                        <input type="text" disabled class="layui-input" name="packName" id="packName" placeholder="包装名称"/>
                                    </div>
                                </div>
                                <div class="blocks">
                                    <label>入库单位</label>
                                    <div class="layui-input-inline">
                                        <select type="text"
                                                class="form-control selectpicker bla bla bli "
                                                lay-filter="warehouse"
                                                lay-verify="required"
                                                id="warehouse"
                                                name="warehouse"
                                                placeholder="入库单位">
                                        </select>
                                        <input type="hidden" name="warehouseS" id="warehouseS"/>
                                    </div>
                                </div>
                            </div>
                            <div class="blockout">
                                <div class="blocks">
                                    <label>体积</label>
                                    <div class="layui-input-inline">
                                        <input type="text" disabled class="layui-input" name="volume" id="volume" placeholder="体积"/>
                                        <span hidden id="volumeS"></span>
                                    </div>
                                </div>
                                <div class="blocks">
                                    <label>净重</label>
                                    <div class="layui-input-inline">
                                        <input type="text" disabled class="layui-input" name="suttle" id="suttle" placeholder="净重"/>
                                        <span hidden id="suttleS"></span>
                                    </div>
                                </div>
                                <div class="blocks">
                                    <label>毛重</label>
                                    <div class="layui-input-inline">
                                        <input type="text" disabled class="layui-input" name="grossWeight" id="grossWeight" placeholder="毛重"/>
                                        <span hidden id="grossWeightS"></span>
                                    </div>
                                </div>
                                <div class="blocks">
                                    <label>金额</label>
                                    <div class="layui-input-inline">
                                        <input type="text" disabled class="layui-input" name="money" id="money" placeholder="金额"/>
                                    </div>
                                </div>
                            </div>
                            <div class="blockout" style="width: 73%;">
                                <div class="blocks">
                                    <label>主单位</label>
                                    <div class="layui-input-inline">
                                        <input type="text"
                                               disabled="true"
                                               class="layui-input"
                                               lay-verify="required"
                                               name="unitNumber"
                                               id="unitNumber"
                                               placeholder="主单位"/>
                                    </div>
                                </div>
                                <div class="blocks">
                                    <label>箱单位</label>
                                    <div class="layui-input-inline">
                                        <input type="text"
                                               disabled="true"
                                               class="layui-input"
                                               lay-verify="required"
                                               name="boxNumber"
                                               id="boxNumber"
                                               placeholder="箱单位"/>
                                    </div>
                                </div>
                                <div class="blocks">
                                    <label>总金额</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" name="numMoney" id="numMoney" />
                                    </div>
                                </div>
                            </div>
                            <div class="blockout">
                                <div class="blocks" style="width: 69%">
                                    <label>备注</label>
                                    <div class="layui-input-inline">
                                        <input type="text" class="layui-input" name="datailRemark" id="datailRemark"/>
                                    </div>
                                </div>
                                <span hidden id="INDEXS"></span>
                                <input type="hidden" name="rowId" id="rowId" />
                                <input type="hidden" name="sscgdid" id="sscgdid"/>
                                <div class="blocks">
                                    <div class="layui-input-inline" style="margin-top: 2rem;">
                                        <!--<a class="layui-btn" onclick="detailSave()">保存</a>-->
                                        <button class="layui-btn" lay-submit lay-filter="add">保存</button>
                                        <button id="cancel" type="reset" class="layui-btn layui-btn-primary">取消</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <button class="layui-btn" id="addInfor">新增</button>
            <section class="panel panel-padding layui-card-body" >
                <div class="pro">
                    <table id="table"></table>
                </div>
            </section>
        </div>
    </div>
</div>
</body>
<div th:include="public/public_js::public_js"></div>
<script th:src="@{plugin/beyond/assets/js/fuelux/wizard/wizard-custom.js}"></script>

<script>

    var indexs = 0;
    
    function returnpage() {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    }
    // 查询入库单位
    function wareHouseUnit(id) {
        var DATA;
        $.ajax({
            url: '/zxsswms/wmsPurchaseOrder/packDetailList/' + id,
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json',
            async: false,
            success: function (data) {
                DATA = data;
            }
        })
        return DATA;
    }

    function toFixeds (data) {
        var str = "";
        if (data !== '') {
            data = data.toString();
            if (data.indexOf('.') < 0) {
                str = data;
            } else {
                str = data.substring(0, data.indexOf('.') + 3);
            }
            return parseFloat(str);
        }
    }

    // option渲染方法
    function optionRendering(data, value, text) {
        var optionInf = '<option value="">请选择</option>';
        data.forEach(function (item) {
            optionInf += '<option value="'+ item[value] +'">'+ item[text] +'</option>';
        })
        return optionInf;
    }

    // 根据包装类型判断主单位是否禁用
    function packageType(type) {
        if (type == 0) {
            $('#unitNumber').attr("disabled",false);
            $('#boxNumber').attr("disabled",true);
        } else {
            $('#unitNumber').attr("disabled",true);
            $('#boxNumber').attr("disabled",false);
        }
    }

    layui.use(['myform','zzpUtils','form','laydate','jquery','zzpValidation'],function () {
        var form = layui.form,
            zzpUtils = layui.zzpUtils
            ,laydate = layui.laydate
            ,zzpValidation = layui.zzpValidation
            ,$ = layui.jquery;
        var saveType = 'add';
        var GOODSCode;

        // 行内按钮
        window.operateEvent ={
            // 触发table行内回显
            "click #editRow":function (e, value, row, index) {
                $('#addInf').css('display', 'block');
                saveType = 'edit';
                $('#addInfor').css('display', 'none');
//                var Row;
//                console.log('rrrrrrrrrr', row, GOODSCode);
//                for (let i = 0; i < GOODSCode.length; i++) {
//                    let item = GOODSCode[i];
//                    if (item.goodsId == row.hpid) {
//                        Row = item;
//                        break;
//                    }
//                }
                var ids = {'bh': row.bh, 'gysid': supplierId};
//                var ids;
//                console.log('RRRRRRRRRRRRR', Row);
//                if (Row) {
//                    ids = {'bh': Row.goodsBh, 'gysid': supplierId};
//                }
                var goodsCodeData = goodsCode(ids);
                var warehouse = wareHouseUnit(goodsCodeData[0].packId);
                warehouseOption(warehouse);// 给入库单位赋option
                var warehouseSel = [];
                // 获取选中的入库单位
                warehouse.forEach(function (item) {
                    if (item.ms === row.ms) {
                        warehouseSel.push(item);
                    }
                });
                var warehousesel = warehouseSel[0];
                $('#goodsCode').val(row.hpid);
                $('#goodsName').val(row.mc);
                $('#packName').val(row.bzmc);
                $('#warehouse').val(row.ms);
                form.render('select');
                $('#volume').val(row.tj);
                $('#suttle').val(row.jz);
                $('#numMoney').val(row.je);
                $('#unitNumber').val(row.sl);
                $('#boxNumber').val(row.xdwsl);
                $('#datailRemark').val(row.bz);
                $('#rowId').val(row.id);
                if (row.sscgdid) {
                    $('#sscgdid').val(row.sscgdid);
                }
                if (warehouseSel.length !== 0) {
                    $('#volumeS').text(warehousesel.tj);
                    $('#suttleS').text(warehousesel.jz);
                    $('#grossWeight').val(warehousesel.zl * row.sl);
                    $('#grossWeightS').text(warehousesel.zl);
                    $('#money').val(warehousesel.je);
                }
            },
            "click #delete":function (e, value, row, index) {
                console.log('触发了删除', row);
                let ids = [];
                ids.push(row.id);
                let data = {
                    id: localStorage['id'],
                    ids: ids,
                }
                $.ajax({
                    url: '/zxsswms/wmsPurchaseOrderDetailed/delete',
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify(data),
                    success: function (data) {
                        layer.msg(data.message);
                        if (data.type === 'success') {
                            refresh();
                        }
                    }
                })
            },
        }

        function operateFormatter(value, row, index) {
            return [
                '<a class="layui-btn layui-btn-xs" id="editRow">编辑</a>',
                '<a class="layui-btn layui-btn-danger layui-btn-xs" id="delete">删除</a>'
            ].join('')
        }

        var supplierId = localStorage['gysid'];
        var blanktable = layui.zzpUtils.table({
            elem: '#table',
            isApi: true,
            pagination: false,//分页开关
    checkboxHeader: false,
            showColumns: false,// 列选择
            columns: [
                {field:'bh',title:'货品编号'},
                {field:'mc',title:'货品名称'},
                {field:'bzmc',title:'包装名称'},
                {field:'hgl',title:'合格率'},
                {field:'sl',title:'主单位数量'},
                {field:'ms',title:'主单位'},
                {field:'xdwsl',title:'箱单位数量'},
                {field:'je',title:'金额'},
                {field:'bz',title:'备注'},
                {
                    field:'caozuo',
                    title: '操作',
                    events: operateEvent,
                    formatter: operateFormatter
                }
            ],
            onLoadError: function(){  //	远程数据加载失败时触发。
                if(localStorage['shzt'] == '1'){
                    $('#table').bootstrapTable('hideColumn', 'caozuo');
                }
            }
        });

        $(function () {
            var shzt = localStorage['shzt'];
            if (shzt === '0') {
                $('#addInfor').css('display', 'block');
                var gysid = {'gysid': supplierId};
                // 查询货品编号
                GOODSCode = goodsCode(gysid);
                var optionInf = optionRendering(GOODSCode, 'goodsId', 'goodsBh');
                // 给货品编号赋option
                $('#goodsCode').append(optionInf);
                // 重新渲染form，否则新的option不显示
                form.render();
            }
            var tabledata = queryGood();
            blanktable.bootstrapTable('append', tabledata);
        })

        function queryGood(){
            var TableDATA;
            $.ajax({
                url: '/zxsswms/wmsPurchaseOrder/wmsPurchaseOrderDetailList/' + localStorage['id'],
                type: 'GET',
                dataType: 'json',
                contentType: 'application/json',
                async: false,
                success: function (data) {
                    if (data) {
                        TableDATA = data;
                    }
                }
            })
            return TableDATA;
        }

        //查询货品编号
        function goodsCode(ids) {
            var DATA;
            $.ajax({
                url: '/zxsswms/wmsPurchaseOrder/getGoods',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify(ids),
                async: false,
                success: function (data) {
                    DATA = data;
                }
            })
            return DATA;
        }

        // 货品编号选中触发
        form.on('select(goodsCode)', function (data) {
            if (data) {
                var text = $("#goodsCode").find("option:selected").text();
                var ids = {'bh': text, 'gysid': supplierId};
                var goodsCodeData = goodsCode(ids)[0];
                var packId = goodsCodeData.packId;
                var warehouseunit = wareHouseUnit(packId);
                warehouseOption(warehouseunit);
                $('#goodsName').val(goodsCodeData.goodsName);//包装名称
                $('#packName').val(goodsCodeData.bzmc);//货品名称
                $('#warehouse').val('');//重置入库单位
                form.render('select');
                $('#volume').val(0);
                $('#suttle').val(0);
                $('#grossWeight').val(0);
                $('#money').val(0);
            }
        })
        
        function warehouseOption(warehouseunit) {
            $('#warehouse').find("option").remove();
            var options = '<option value="">请选择</option>';
            warehouseunit.forEach(function (item) {
                options += "<option title='"+ JSON.stringify(item) +"' value='"+ item.ms +"'>"+ item.ms +"</option>";
            });
            $('#warehouse').append(options);
            form.render();
        }

        // 入库单位选中触发
        form.on('select(warehouse)', function (data) {
            var datas = $('#warehouse').find("option:selected");
            var wareHouseData = JSON.parse(datas[0].title);
            $('#volume').val(wareHouseData.tj);
            $('#volumeS').text(wareHouseData.tj);

            $('#suttle').val(wareHouseData.jz);
            $('#suttleS').text(wareHouseData.jz);

            $('#grossWeight').val(wareHouseData.zl);
            $('#grossWeightS').text(wareHouseData.zl);

            $('#money').val(wareHouseData.je);
            $('#numMoney').val(0);
            $('#unitNumber').val(0);
            $('#boxNumber').val('0箱0件');
            $('#warehouseS').val(wareHouseData.id);

            packageType(wareHouseData.bzlx);
            // 主单位数量
            UnitNum = wareHouseData.zdwsl;
            UnitType = wareHouseData.bzlx;

        })

        // 监听主单位数量
        $('#unitNumber').on('input propertychange', function(data) {
            var value =  data.currentTarget.value;
            var len, lenfloat;
            var volumeS = parseFloat($('#volumeS').text());
            var suttleS = parseFloat($('#suttleS').text());
            var grossWeightS = parseFloat($('#grossWeightS').text());
            var money = parseFloat($('#money').val());
            // 如果value不为空
            if (value && value !== '0') {
                len = parseInt(value);
                lenfloat = parseFloat(value);
                if (value.indexOf('-') >= 0) {
                    $('#unitNumber').val('');
                } else if ((lenfloat - len) > 0) {
                    $('#unitNumber').val(len);
                } else {
                    $('#volume').val(toFixeds(volumeS * len));
                    $('#suttle').val(toFixeds(suttleS * len));
                    $('#grossWeight').val(toFixeds(grossWeightS * len));
                    $('#numMoney').val(toFixeds(money * len));

                    // 如果主单位数量为1
                    if (UnitNum === 1) {
                        $('#boxNumber').val(len.toString() + '箱0件');
                    } else {
                        var BOX,PIECE;
                        BOX = parseInt(len/UnitNum);
                        PIECE = len%UnitNum;
                        $('#boxNumber').val(BOX + '箱'+ PIECE +'件');
                    }

                }

            } else {
                $('#volume').val(volumeS);
                $('#suttle').val(suttleS);
                $('#grossWeight').val(grossWeightS);
                $('#numMoney').val(0);
                $('#boxNumber').val('0箱0件');
            }

        })

        // 监听箱单位数量
        $('#boxNumber').on('input propertychange', function(data) {
            var value, indbox, indpiece, box, piece, boxs, pieces;
            var volumeS = parseFloat($('#volumeS').text());
            var suttleS = parseFloat($('#suttleS').text());
            var grossWeightS = parseFloat($('#grossWeightS').text());
            var money = parseFloat($('#money').val());
            value =  data.currentTarget.value;
            indbox = value.indexOf('箱');
            indpiece = value.indexOf('件');
            box = value.substring(0, indbox);
            piece = value.substring(indbox + 1,  indpiece);
            boxs = parseFloat(box) - parseInt(box);
            pieces = parseFloat(piece) - parseInt(piece);
            if (boxs > 0 && pieces > 0) {
                $('#unitNumber').val(box + '箱'+ piece +'件');
            }
            if (boxs < 0 && pieces > 0) {
                $('#unitNumber').val(Math.abs(box) + '箱'+ piece +'件');
            }
            if (boxs > 0 && pieces < 0) {
                $('#unitNumber').val(box + '箱'+ Math.abs(piece) +'件');
            }
            if (parseInt(box) >= 0 && parseInt(piece) >= 0) {
                var unitNumber = parseInt(box) * UnitNum + parseInt(piece);
                var len;
                if (unitNumber !== 0) {
                    len = unitNumber;
                    $('#numMoney').val(toFixeds(money * len));
                } else {
                    len = 1;
                    $('#numMoney').val(0);
                }
                $('#unitNumber').val(unitNumber);
                $('#volume').val(toFixeds(volumeS * len));
                $('#suttle').val(toFixeds(suttleS * len));
                $('#grossWeight').val(toFixeds(grossWeightS * len));

            }
        })

        // 新增按钮触发
        $('#addInfor').click(function () {
            $('#addInf').css('display', 'block');
            saveType = 'add';
            $('#addInfor').css('display', 'none');
            //重置form
            $('#form1 input').val('');
            $('#warehouse').val('');
            $('#goodsCode').val('');
            form.render();
        })
        // 执行保存
        form.on("submit(add)",function(data){
            var field = data.field;
            $('#addInfor').css('display', 'block');
            var SaveData = {};
            SaveData.bh = $("#goodsCode").find("option:selected").text();// 货品编号
            SaveData.mc = field.packName;
            SaveData.bzmc = field.packName;
            SaveData.hpid = field.goodsCode;
            SaveData.je = field.numMoney;
            SaveData.jz = field.grossWeight;
            SaveData.sl = field.unitNumber;
            SaveData.jz = field.grossWeight;
            SaveData.tj = field.volume;
            SaveData.ms = field.warehouse;
            SaveData.xdwsl = field.boxNumber;
            SaveData.bz = field.datailRemark;
            SaveData.zdw = field.warehouseS;
            if (saveType === 'add') {
                SaveData.sscgdid = localStorage['id'];
                console.log('执行了新增');
                $('#addInf').css('display', 'none');
                var types;
                $.ajax({
                    url: '/zxsswms/wmsPurchaseOrderDetailed/add',
                    type: 'POST',
                    dataType: 'json',
                    contentType:"application/json;charset=UTF-8",
                    data: JSON.stringify(SaveData),
                    async: false,
                    success: function (data) {
                        layer.msg(data.message);
                        if (data.type === 'success') {
                            refresh();
                        }
                    },
                    error: function (err) {

                    }
                })

            }
            if (saveType === 'edit') {
                console.log('执行了修改');
                SaveData.id = field.rowId;
                SaveData.sscgdid = field.sscgdid;
                var tabledata2;
                $('#addInf').css('display', 'none');
                $.ajax({
                    url: '/zxsswms/wmsPurchaseOrderDetailed/edit',
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify(SaveData),
                    success: function (data) {
                        layer.msg(data.message);
                        if (data.type === 'success') {
                            refresh();
                        }
                    },
                    error: function (err) {

                    }
                })
            }
            return false;
        })
        
        function refresh() {
            var tabledata = blanktable.bootstrapTable('getData');
            var tabledata1 = queryGood();
            blanktable.bootstrapTable('removeAll');
            blanktable.bootstrapTable('append', tabledata1);
        }

        // 取消且重置form
        $('#cancel').click(function () {
            $('#addInf').css('display', 'none');
            $('#addInfor').css('display', 'block');
        })

        function tableSave(data) {
            if (data.ms !== '') {
                if(data.sl !== '') {
                    var blanktableData = blanktable.bootstrapTable('getData');
                    if (blanktableData.length === 0) {
                        data.index = 0;
                        blanktable.bootstrapTable('append', data);
                    } else {
                        console.log('table不为空');
                        var type = blanktableData.every(function (item) {
                            return item.hpid !== data.hpid;
                        });
                        if (type) {
                            console.log('执行添加');
                            indexs += 1;
                            data.index = indexs;
                            blanktable.bootstrapTable('append', data);
                        } else {
                            console.log('执行更新');
                            var In = parseInt($('#INDEXS').text());
                            blanktable.bootstrapTable('updateRow', {index: In, row: data});
                        }
                    }
                } else {
                    layer.msg('您必选填写主单位或箱单位');
                }
            } else {
                layer.msg('您必选选择货品和入库单位');
            }

            $('#orderDetail input[type="text"]').val('');
        }
    });
</script>
</html>